package edu.cug.water.crawler.config;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

@Component("notice")
@Slf4j
public class NoticeConfig {

    private final static String API_KEY = "22c8e3a56195c7f2ef91a71aae3c4a17";

    private final static String API_URL = "https://qmsg.zendee.cn/send/" + API_KEY;

    // 接口响应格式
    /**
     * {
     *     "success": true,
     *     "reason": "操作成功",
     *     "code": 0,
     *     "info": {}
     * }
     */

    @Autowired
    RestTemplate httpsRestTemplate;

    public boolean sendQQMsg(String msg) {

        HttpHeaders header = new HttpHeaders();
        header.add("Content-Type", "application/x-www-form-urlencoded");
        header.add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36");

        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();

        map.add("msg", msg);
        map.add("qq", "554417388");

        HttpEntity<MultiValueMap> entity = new HttpEntity<MultiValueMap>(map, header);

        ResponseEntity<String> response = httpsRestTemplate.exchange(API_URL, HttpMethod.POST, entity, String.class);


        log.info("QQ消息推送相应码 : {}", response.getStatusCodeValue());

        String body = response.getBody();
        log.info("repsonse body :\n {}", body);
        if (!("".equals(body) || body == null)) return false;

        JSONObject parse = (JSONObject) JSONObject.parse(body);
        if (parse.getBooleanValue("success")) return true;
        return false;
    }
}
